import 'package:flutter/material.dart';
import 'package:test/components/swiper_tabs/swiper_tabs_style.dart';
import 'package:test/vendors/tdesign_flutter/lib/tdesign_flutter.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';

typedef ChangeEventHandler = void Function();

class SwiperTabs extends StatefulWidget {
  const SwiperTabs(
      {
        required this.titles,
        required this.children,
        this.style,
        this.onIndexChanged,
        Key? key})
      : super(key: key);
  /// 操作按钮文案
  final List<Widget>? children;
  final List<String> titles;
  final SwiperTabsStyle? style;
  /// 标签页改变时的处理函数
  final ChangeEventHandler? onIndexChanged;
  
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _SwiperTabsState();
  }
}

class _SwiperTabsState extends State<SwiperTabs> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  late SwiperController _swiperController;

  @override
  void initState() {
    // 初始化 TabController，这里有 3 个标签页
    _tabController = TabController(length: 3, vsync: this);
    _swiperController = SwiperController();
    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        print('正在切换到第 ${_tabController.index} 个标签页');
        _swiperController.move(_tabController.index);
      } else {
        print('当前标签页索引: ${_tabController.index}');
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    // 释放 TabController
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          SizedBox(
            height: 100,
            child: TDTabBar(
              // 使用 TabController 控制标签页切换
              controller: _tabController,
              tabs: widget.titles.map((title) => TDTab(text: title)).toList(),
            ),
          ),
          Expanded(
            child: Swiper(
              autoplay: false,
              itemCount: widget.children?.length ?? 0,
              loop: false,
              controller: _swiperController,
              itemBuilder: (BuildContext context, int index) {
                return Center(child: widget.children?[index]);
              },
              onIndexChanged: (int index) {
                print('当前轮播页索引: $index');
                _tabController.animateTo(index);
              },
            ),
          )
        ],
      ),
    );
  }
}
